<?php

class ProfileController extends BaseController {
    
    public function actionProfile($login) {
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) $user = Yii::app()->user->getAllUserInfo();
        else $user = Yii::app()->db->createCommand()->select('*')->from('users')->where("login=\"$login\"")->queryRow();
        if(empty($user)) throw new CHttpException(404);
        $this->options = Yii::app()->db->createCommand(array('select'=>'val, name', 'from'=>'options'))->queryAll();
        $delegatePart = Yii::app()->db->createCommand()->select('p.name, p.catId, p.url, pc.parentId')->from('partners p')->leftJoin('partners_cat pc', 'pc.catId=p.catId')->where('delegate1='.$user['userid'].' or delegate2='.$user['userid'])->queryAll();
        $workPart = Yii::app()->db->createCommand()->select('pu.partnerId, p.name as partnerName, p.url, p.catId, pc.parentId')->from('partners_users pu')->leftJoin('partners p', 'p.partnerid=pu.partnerId')->leftJoin('partners_cat pc', 'pc.catId=p.catId')->where('pu.userId='.$user['userid'])->queryAll();
//        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
//            $reviews = Yii::app()->db->createCommand()->select('r.revId, r.text, r.countComments, r.date, r.url, p.partnerid, r.title, r.status, p.name, p.url as partnerUrl, p.catId, c.parentId, c.name as catName')->from('reviews r')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('r.userId='.$user['userid'])->limit(3)->order('date DESC')->queryAll();
//        } else 
        $reviews = Yii::app()->db->createCommand()->select('r.revId, r.text, r.countComments, r.date, r.averageRating, r.url, p.partnerid, r.title, r.status, r.isAnonym, p.name, p.url as partnerUrl, p.catId, c.parentId, c.name as catName')->from('reviews r')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('r.userId='.$user['userid'].' and r.status not in ("Отклонен", "Новый", "В работе") and r.isAnonym=0')->limit(3)->order('date DESC')->queryAll();
        $count = array();
        if(!empty($reviews)) {
            if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) 
                $count['reviews'] = Yii::app()->db->createCommand()->select('count(*) as count')->from('reviews')->where('userId='.$user['userid'].' and status not like "Отклонен"')->queryRow();
            foreach($reviews as $i) $idArr[] = $i['partnerid'];
            if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
                $countNewComm = Yii::app()->db->createCommand("SELECT COUNT(*) as count, revId FROM reviews_comments WHERE isNew=".$user['userid']." and revId IN(".implode(',', $idArr).") GROUP BY revId")->query()->readAll();
                for($i=0; $i<count($reviews); $i++) {
                    $reviews[$i]['countNewCom'] = 0;
                    for($j=0; $j<count($countNewComm); $j++)
                        if($countNewComm[$j]['revId'] == $reviews[$i]['revId'])
                            $reviews[$i]['countNewCom'] = $countNewComm[$j]['count'];
                }   
            }
            $reviewsSubcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($reviewsSubcats)) {
                for($i=0; $i<count($reviews); $i++) {
                    for($j=0;$j<count($reviewsSubcats);$j++)
                        if($reviews[$i]['partnerid'] == $reviewsSubcats[$j]['partnerId']) $reviews[$i]['subCats'][] = $reviewsSubcats[$j];
                }
            }
        }
        $messages = Yii::app()->db->createCommand()->select('c.themeId, c.text, c.comDate, c.isFirst, t.title, t.url, p.partnerid, p.name, p.url as partnerUrl, pc.catId, pc.parentId, pc.name as catName')->from('forum_comments c')->where('c.userId='.$user['userid'])->leftJoin('forum_theme t', 't.themeId=c.themeId')->leftJoin('partners p', 'p.partnerid=t.partnerid')->leftJoin('partners_cat pc', 'pc.catId=p.catId')->order('c.comDate DESC')->limit(3)->queryAll();
        if(!empty($messages)) {
            if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) 
                $count['messages'] = Yii::app()->db->createCommand()->select('count(*) as count')->from('forum_comments')->where('userid='.$user['userid'])->queryRow();
            foreach ($messages as $i) $idArr[] = $i['partnerid'];
            $messagesSubCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($messagesSubCats)) {
                for($i=0; $i<count($messages); $i++) {
                    for($j=0;$j<count($messagesSubCats);$j++)
                        if($messages[$i]['partnerid'] == $messagesSubCats[$j]['partnerId']) $messages[$i]['subCats'][] = $messagesSubCats[$j];
                }
            }
        }
//        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
//            $revComments = Yii::app()->db->createCommand()->select('t.text, t.date, t.revId, r.title, r.url, p.name, p.url as partnerUrl, p.partnerid, p.catId, c.parentId, c.name as catName, t.comId')->from('reviews_comments t')->join('reviews r', 'r.revId=t.revId')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('t.userId='.$user['userid'])->limit(3)->order('date DESC')->queryAll();
//        } else 
        $revComments = Yii::app()->db->createCommand()->select('t.text, t.date, t.revId, r.title, r.url, p.name, p.url as partnerUrl, p.partnerid, p.catId, c.parentId, c.name as catName, t.comId')->from('reviews_comments t')->join('reviews r', 'r.revId=t.revId')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('t.isAnonym=0 and t.userId='.$user['userid'])->limit(3)->order('date DESC')->queryAll();
        if(!empty($revComments)) {
            if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) 
                $count['revComments'] = Yii::app()->db->createCommand()->select('count(*) as count')->from('reviews_comments')->where('userid='.$user['userid'].' and isAnonym=0')->queryRow();
            $idArr = array();
            foreach($revComments as $i) $idArr[] = $i['partnerid'];
            $revComSubcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($revComSubcats)) {
                for($i=0; $i<count($revComments); $i++) {
                    for($j=0;$j<count($revComSubcats);$j++)
                        if($revComments[$i]['partnerid'] == $revComSubcats[$j]['partnerId']) $revComments[$i]['subCats'][] = $revComSubcats[$j];
                }
            }
        }
        $this->render('profile', array('revComments'=>$revComments, 'countData'=>$count, 'user'=>$user, 'messages'=>$messages, 'reviews'=>$reviews, 'revComments'=>$revComments, 'workPart'=>$workPart, 'delegatePart'=>$delegatePart));
    }    
    
    public function actionEdit() {
        $model = User::model()->findByPk(Yii::app()->user->getId());
        if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            $image = CUploadedFile::getInstance($model, 'avatar');
            if($image) $model->setScenario('uploadAvatar');
            if($model->validate()) {
                if($image) {
                    $model->avatar = md5( rand(0,10000) . $image->getName() . microtime() ).'.'.$image->getExtensionName();
                    $image->saveAs(Yii::getPathOfAlias('webroot').'/images/uploads/userAvatars/'.$model->avatar);
                    if(Yii::app()->user->getState('avatar') && file_exists(Yii::getPathOfAlias('webroot').'/images/userAvatars/'.Yii::app()->user->getState('avatar'))) unlink (Yii::getPathOfAlias('webroot').'/images/uploads/userAvatars/'.Yii::app()->user->getState('avatar'));
                }
                if($model->save(false)) $this->redirect(array('profile/profile', 'login'=>Yii::app()->user->getState('login')));
            }
        }
        $this->render('edit', array('model'=>$model));
    }
    
    public function actionReviews($login) {
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) $user = Yii::app()->user->getAllUserInfo();
        else $user = Yii::app()->db->createCommand()->select('*')->from('users')->where("login=\"$login\"")->queryRow();
        if(empty($user)) throw new CHttpException(404);
        $this->options = Yii::app()->db->createCommand(array('select'=>'val, name', 'from'=>'options'))->queryAll();
        
        $countItems = Yii::app()->db->createCommand()->select('count(*)')->from('reviews')->where('userId='.$user['userid'])->queryRow();
        $pagination = new CPagination($countItems['count(*)']);
        $pagination->setPageSize(15);
        
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
            $reviews = Yii::app()->db->createCommand()->select('r.revId, r.text, r.averageRating, r.countComments, r.date, r.url, r.title, r.status, p.name, p.url as partnerUrl, p.partnerid, p.catId, c.parentId, c.name as catName')->from('reviews r')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('r.userId='.$user['userid'])->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
        } else $reviews = Yii::app()->db->createCommand()->select('r.revId, r.text, r.countComments, r.averageRating, r.date, r.url, r.title, r.status, p.name, p.url as partnerUrl, p.partnerid, p.catId, c.parentId, c.name as catName')->from('reviews r')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('r.userId='.$user['userid'].' and r.status not like "Отклонен" and isAnonym=0')->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
        
        if(!empty($reviews)) {
            foreach($reviews as $i) $idArr[] = $i['partnerid'];
            if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
                $countNewComm = Yii::app()->db->createCommand("SELECT COUNT(*) as count, revId FROM reviews_comments WHERE isNew=".$user['userid']." and revId IN(".implode(',', $idArr).") GROUP BY revId")->query()->readAll();
            }
            for($i=0; $i<count($reviews); $i++) {
                $reviews[$i]['countNewCom'] = 0;
                for($j=0; $j<count($countNewComm); $j++)
                    if($countNewComm[$j]['revId'] == $reviews[$i]['revId'])
                        $reviews[$i]['countNewCom'] = $countNewComm[$j]['count'];
            }
            
            $reviewsSubcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($reviewsSubcats)) {
                for($i=0; $i<count($reviews); $i++) {
                    for($j=0;$j<count($reviewsSubcats);$j++)
                        if($reviews[$i]['partnerid'] == $reviewsSubcats[$j]['partnerId']) 
                            $reviews[$i]['subCats'][] = $reviewsSubcats[$j];
                }
            }
        }
        $this->render('reviews', array('user'=>$user, 'reviews'=>$reviews, 'pagination'=>$pagination));
    }

    public function actionComments($login) {
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) $user = Yii::app()->user->getAllUserInfo();
        else $user = Yii::app()->db->createCommand()->select('*')->from('users')->where("login=\"$login\"")->queryRow();
        if(empty($user)) throw new CHttpException(404);
        
        $countItems = Yii::app()->db->createCommand()->select('count(*)')->from('reviews_comments')->where('userId='.$user['userid'])->queryRow();
        $pagination = new CPagination($countItems['count(*)']);
        $pagination->setPageSize(15);
        
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) {
            $revComments = Yii::app()->db->createCommand()->select('t.text, t.date, t.revId, r.title, r.url, p.name, p.url as partnerUrl, p.partnerid, p.catId, c.parentId, c.name as catName')->from('reviews_comments t')->join('reviews r', 'r.revId=t.revId')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('t.userId='.$user['userid'])->limit($pagination->getLimit())->offset($pagination->getOffset())->order('date DESC')->queryAll();
        } else $revComments = Yii::app()->db->createCommand()->select('t.text, t.date, t.revId, r.title, r.url, p.name, p.url as partnerUrl, p.catId, p.partnerid, c.parentId, c.name as catName')->from('reviews_comments t')->join('reviews r', 'r.revId=t.revId')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('t.isAnonym=0 and t.userId='.$user['userid'])->limit($pagination->getLimit())->offset($pagination->getOffset())->order('date DESC')->queryAll();
        if(!empty($revComments)) {
            foreach($revComments as $i) $idArr[] = $i['partnerid'];
            $revComSubcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($revComSubcats)) {
                for($i=0; $i<count($revComments); $i++) {
                    for($j=0;$j<count($revComSubcats);$j++)
                        if($revComments[$i]['partnerid'] == $revComSubcats[$j]['partnerId']) $revComments[$i]['subCats'][] = $revComSubcats[$j];
                }
            }
        }
        $this->render('comments', array('user'=>$user, 'revComments'=>$revComments, 'pagination'=>$pagination));
    }
    
    public function actionPosts($login) {
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) $user = Yii::app()->user->getAllUserInfo();
        else $user = Yii::app()->db->createCommand()->select('*')->from('users')->where("login=\"$login\"")->queryRow();
        if(empty($user)) throw new CHttpException(404);
        
        $countItems = Yii::app()->db->createCommand()->select('count(*)')->from('forum_comments')->where('userId='.$user['userid'])->queryRow();
        $pagination = new CPagination($countItems['count(*)']);
        $pagination->setPageSize(15);
        
        $messages = Yii::app()->db->createCommand()->select('c.themeId, c.text, c.comDate, c.isFirst, t.title, t.url, p.partnerid, p.name, p.url as partnerUrl, pc.catId, pc.parentId, pc.name as catName')->from('forum_comments c')->where('c.userId='.$user['userid'])->leftJoin('forum_theme t', 't.themeId=c.themeId')->leftJoin('partners p', 'p.partnerid=t.partnerid')->leftJoin('partners_cat pc', 'pc.catId=p.catId')->order('c.comDate DESC')->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
        if(!empty($messages)) {
            foreach ($messages as $i) $idArr[] = $i['partnerid']; 
            $subcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($subcats)) {
                for($i=0; $i<count($messages); $i++) {
                    for($j=0;$j<count($subcats);$j++)
                        if($messages[$i]['partnerid'] == $subcats[$j]['partnerId']) $messages[$i]['subCats'][] = $subcats[$j];
                }
            }
        }
        $this->render('posts', array('user'=>$user, 'messages'=>$messages, 'pagination'=>$pagination));
    }
    
    public function actionNewRevComm($login) {
        if(!Yii::app()->user->isGuest && $login == Yii::app()->user->getState('login')) $user = Yii::app()->user->getAllUserInfo();
        else $user = Yii::app()->db->createCommand()->select('*')->from('users')->where("login=\"$login\"")->queryRow();
        if(empty($user)) throw new CHttpException(404);
        
        $reviews = Yii::app()->db->createCommand()->select('r.revId, r.title, r.url, p.url as partnerUrl, p.catId, c.parentId, c.name as catName, p.name')->from('reviews r')->leftJoin('partners p', 'p.partnerid=r.partnerid')->leftJoin('partners_cat c', 'c.catId=p.catId')->where('r.status not in("Новый", "В работе", "Отклонен") and r.userId='.$user['userid'])->queryAll();
        $idArr = array();
        for($i=0; $i<count($reviews); $i++) $idArr[] = $reviews[$i]['revId'];
        $countItems = Yii::app()->db->createCommand()->select('count(*)')->from('reviews_comments')->where(array('in', 'revId', $idArr))->queryRow();
        
        $pagination = new CPagination($countItems['count(*)']);
        $pagination->setPageSize(15);
        
        $comments = Yii::app()->db->createCommand()->select('c.date, c.text, c.isAnonym, c.isNew, u.login, u.avatar, c.revId, c.comId, r.partnerId')->from('reviews_comments c')->join('reviews r', 'r.revId=c.revId')->join('users u', 'u.userid=c.userId')->where(array('in', 'c.revId', $idArr))->limit($pagination->getLimit())->offset($pagination->getOffset())->order('date asc')->queryAll();
        if(!empty($comments)) {
            foreach($comments as $i) $idArr[] = $i['partnerId'];
            $revComSubcats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($revComSubcats)) {
                for($i=0; $i<count($comments); $i++) {
                    for($j=0;$j<count($revComSubcats);$j++)
                        if($comments[$i]['partnerId'] == $revComSubcats[$j]['partnerId']) $comments[$i]['subCats'][] = $revComSubcats[$j];
                }
            }
            if(!Yii::app()->user->isGuest) {
                $idArr = array();
                foreach ($comments as $c) $idArr[] = $c['comId'];
                Yii::app()->db->createCommand()->update('reviews_comments', array('isNew'=>0), '`isNew`='.Yii::app()->user->getId().' and `comId` IN('.implode(',', $idArr).')');
            } 
        }
        $this->render('newRevComm', array('user'=>$user, 'comments'=>$comments, 'pagination'=>$pagination, 'reviews'=>$reviews));
    }
}